<template>
  <div class="app-container">
    <div class="page-header">
      <h2 class="page-title">资源管理</h2>
    </div>
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="资源ID" prop="resource_id">
        <el-input
          v-model="queryParams.resource_id"
          placeholder="请输入资源ID"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资源名称" prop="resource_name">
        <el-input
          v-model="queryParams.resource_name"
          placeholder="请输入资源名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资源类型" prop="resource_type">
        <el-select
          v-model="queryParams.resource_type"
          placeholder="请选择资源类型"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="dict in resourceTypeOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="服务主机" prop="resource_host">
        <el-input
          v-model="queryParams.resource_host"
          placeholder="请输入服务主机"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="服务状态" prop="resource_status">
        <el-select
          v-model="queryParams.resource_status"
          placeholder="请选择服务状态"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleBatchDelete"
          >批量删除</el-button
        >
      </el-col>
      <right-toolbar v-model="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="resourceList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="资源ID" align="center" prop="resourceId" />
      <el-table-column label="服务主机" align="center" prop="host" />
      <el-table-column label="资源名称" align="center" prop="resourceName" />
      <el-table-column label="资源类型" align="center" prop="resourceType">
        <template #default="scope">
          <dict-tag
            :options="resourceTypeOptions"
            :value="scope.row.resourceType"
          />
        </template>
      </el-table-column>
      <el-table-column label="资源状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="280"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <div class="operation-buttons">
            <el-tooltip content="扩充资源" placement="top">
              <el-button
                type="primary"
                link
                icon="Plus"
                @click="handleExpand(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="编辑资源" placement="top">
              <el-button
                type="primary"
                link
                icon="Edit"
                @click="handleUpdate(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除资源" placement="top">
              <el-button
                type="primary"
                link
                icon="Delete"
                @click="handleDelete(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="停止资源" placement="top">
              <el-button
                type="primary"
                link
                icon="VideoPause"
                @click="handleStop(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="启动资源" placement="top">
              <el-button
                type="primary"
                link
                icon="VideoPlay"
                @click="handleStart(scope.row)"
              ></el-button>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page="queryParams.pageNum"
      :limit="queryParams.pageSize"
      @update:page="(val) => (queryParams.pageNum = val)"
      @update:limit="(val) => (queryParams.pageSize = val)"
      @pagination="getList"
    />

    <!-- 添加或修改资源对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form
        ref="resourceRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="资源名称" prop="resource_name">
          <el-input
            v-model="form.resource_name"
            placeholder="请输入资源名称"
            :disabled="isEdit && !canEditFields.includes('resource_name')"
          />
        </el-form-item>
        <el-form-item label="资源类型" prop="resource_type">
          <el-select
            v-model="form.resource_type"
            placeholder="请选择资源类型"
            style="width: 100%"
            :disabled="isEdit || isExpand"
          >
            <el-option
              v-for="dict in resourceTypeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务主机" prop="resource_host">
          <el-input
            v-model="form.resource_host"
            placeholder="请输入服务主机"
            style="width: 100%"
            :disabled="isEdit || isExpand"
          />
        </el-form-item>
        <el-form-item label="服务端口" prop="resource_port">
          <el-input-number
            v-model="form.resource_port"
            placeholder="请输入服务端口"
            :min="1"
            :max="65535"
            style="width: 100%"
            :disabled="isEdit || isExpand"
          />
        </el-form-item>
        <el-form-item label="Python版本" prop="python_version">
          <el-select
            v-model="form.python_version"
            placeholder="请选择Python版本"
            style="width: 100%"
            :disabled="isEdit || isExpand"
          >
            <el-option
              v-for="version in pythonVersionOptions"
              :key="version.value"
              :label="version.label"
              :value="version.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="第三方环境" prop="requirementFileId">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :on-change="handleEnvFileChange"
            :limit="1"
            :disabled="isEdit || isExpand"
          >
            <template #trigger>
              <el-button type="primary" :disabled="isEdit || isExpand"
                >选择文件</el-button
              >
            </template>
            <template #tip>
              <div class="el-upload__tip">请上传requirements.txt文件</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="Redis地址" prop="redis_url">
          <el-input
            v-model="form.redis_url"
            placeholder="请输入Redis地址"
            :disabled="isEdit || isExpand"
          />
        </el-form-item>
        <el-form-item label="扩容方式" prop="capacity_mode">
          <el-select
            v-model="form.capacity_mode"
            placeholder="请选择扩容方式"
            style="width: 100%"
            @change="handleExpandTypeChange"
            :disabled="isEdit && !canEditFields.includes('capacity_mode')"
          >
            <el-option
              v-for="mode in capacityModeOptions"
              :key="mode.value"
              :label="mode.label"
              :value="mode.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="容量大小" prop="capacity_size">
          <el-input-number
            v-model="form.capacity_size"
            :min="1"
            :max="100"
            :disabled="isEdit && !canEditFields.includes('capacity_size')"
          />
        </el-form-item>
        <el-form-item label="资源描述" prop="resource_description">
          <el-input
            v-model="form.resource_description"
            type="textarea"
            placeholder="请输入资源描述"
            :disabled="
              isEdit && !canEditFields.includes('resource_description')
            "
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Resource">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getResourceTypes,
  getResourceStatus,
  getCapacityModes,
  listResource,
  searchResources,
  getResource,
  uploadRequirements,
  addResource,
  updateResource,
  delResource,
  delResourceBatch,
  startResource,
  stopResource,
  replicateResource,
} from "@/api/resource";
import { parseTime } from "@/utils/ruoyi";

const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);
const resourceList = ref([]);
const multiple = ref(true);
const ids = ref([]);

// 资源类型选项
const resourceTypeOptions = ref([]);
// 状态选项
const statusOptions = ref([]);
// 扩容类型选项
const capacityModeOptions = ref([]);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  resource_id: undefined,
  resource_name: undefined,
  resource_type: undefined,
  resource_host: undefined,
  resource_status: undefined,
});

// 表单相关变量
const title = ref("");
const open = ref(false);
const isEdit = ref(false);
const isExpand = ref(false);
const canEditFields = ref([]);
const uploadedFileId = ref("");

const form = ref({
  resource_id: "",
  resource_name: "",
  resource_type: "",
  resource_host: "",
  resource_port: 8080,
  resource_status: "",
  python_version: "",
  resource_description: "",
  redis_url: "",
  capacity_mode: "手动",
  capacity_size: 1,
  requirementFileId: "",
});

const rules = ref({
  resource_name: [
    { required: true, message: "资源名称不能为空", trigger: "blur" },
  ],
  resource_type: [
    { required: true, message: "资源类型不能为空", trigger: "change" },
  ],
  python_version: [
    { required: true, message: "Python版本不能为空", trigger: "change" },
  ],
  resource_description: [
    { required: true, message: "资源描述不能为空", trigger: "blur" },
  ],
  redis_url: [
    { required: true, message: "Redis地址不能为空", trigger: "blur" },
  ],
  capacity_mode: [
    { required: true, message: "扩容方式不能为空", trigger: "change" },
  ],
  capacity_size: [
    { required: true, message: "扩容大小不能为空", trigger: "blur" },
  ],
});

const pythonVersionOptions = ref([
  { value: "3.8", label: "Python 3.8" },
  { value: "3.9", label: "Python 3.9" },
  { value: "3.10", label: "Python 3.10" },
  { value: "3.11", label: "Python 3.11" },
]);

// 获取下拉选项
function fetchOptions() {
  getResourceTypes().then((res) => {
    resourceTypeOptions.value = (res || []).map((item) => ({
      value: item,
      label: item,
    }));
  });
  getResourceStatus().then((res) => {
    statusOptions.value = (res || []).map((item) => ({
      value: item,
      label: item,
    }));
  });
  getCapacityModes().then((res) => {
    capacityModeOptions.value = (res || []).map((item) => ({
      value: item,
      label: item,
    }));
  });
}

/** 查询资源列表（带分页和搜索） */
function getList() {
  loading.value = true;
  // 构造搜索参数
  const params = {};
  if (queryParams.resource_id) params.resource_id = queryParams.resource_id;
  if (queryParams.resource_name)
    params.resource_name = queryParams.resource_name;
  if (queryParams.resource_type)
    params.resource_type = queryParams.resource_type;
  if (queryParams.resource_host)
    params.resource_host = queryParams.resource_host;
  if (queryParams.resource_status)
    params.resource_status = queryParams.resource_status;

  // 如果有搜索条件，走search，否则list
  const fetch = Object.keys(params).length
    ? searchResources(params)
    : listResource();
  fetch
    .then((res) => {
      const data = res || [];
      total.value = data.length;
      const start = (queryParams.pageNum - 1) * queryParams.pageSize;
      const end = start + queryParams.pageSize;
      resourceList.value = data.slice(start, end).map((item) => ({
        resourceId: item.resource_id,
        resourceName: item.resource_name,
        resourceType: item.resource_type,
        host: item.resource_host || item.resource_host,
        port: item.resource_port,
        status: item.resource_status,
        createTime: item.created_at,
        ...item,
      }));
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.resource_id = undefined;
  queryParams.resource_name = undefined;
  queryParams.resource_type = undefined;
  queryParams.resource_host = undefined;
  queryParams.resource_status = undefined;
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  isEdit.value = false;
  isExpand.value = false;
  canEditFields.value = [];
  open.value = true;
  title.value = "添加资源";
}

/** 表单重置 */
function reset() {
  form.value = {
    resource_id: "",
    resource_name: "",
    resource_type: "",
    resource_host: "",
    resource_port: 8080,
    resource_status: "",
    python_version: "",
    resource_description: "",
    redis_url: "",
    capacity_mode: "手动",
    capacity_size: 1,
    requirementFileId: "",
  };
  uploadedFileId.value = "";
  isEdit.value = false;
  isExpand.value = false;
  canEditFields.value = [];
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 处理环境文件上传 */
function handleEnvFileChange(file) {
  if (file.raw) {
    uploadRequirements(file.raw)
      .then((response) => {
        uploadedFileId.value = response.file_id;
        form.value.requirementFileId = response.file_id;
        ElMessage.success("文件上传成功");
      })
      .catch(() => {
        ElMessage.error("文件上传失败");
      });
  }
}

/** 处理扩容方式变化 */
function handleExpandTypeChange(value) {
  form.value.capacity_mode = value;
}

/** 提交按钮 */
function submitForm() {
  if (isEdit.value) {
    if (isExpand.value) {
      // 扩容资源
      const replicateData = {
        resource_host: form.value.resource_host,
        resource_port: form.value.resource_port,
        resource_name: form.value.resource_name,
        resource_type: form.value.resource_type,
        resource_status: form.value.resource_status,
        created_at: new Date().toISOString(),
        python_version: form.value.python_version,
        resource_description: form.value.resource_description,
        redis_url: form.value.redis_url,
        capacity_mode: form.value.capacity_mode,
        capacity_size: form.value.capacity_size,
      };
      replicateResource(form.value.resource_id, replicateData)
        .then(() => {
          ElMessage.success("扩容成功");
          open.value = false;
          getList();
        })
        .catch(() => {
          ElMessage.error("扩容失败");
        });
    } else {
      // 编辑资源
      const updateData = {
        resource_id: form.value.resource_id,
        resource_host: form.value.resource_host,
        resource_port: form.value.resource_port,
        resource_name: form.value.resource_name,
        resource_type: form.value.resource_type,
        resource_status: form.value.resource_status,
        created_at: form.value.created_at,
      };
      updateResource(form.value.resource_id, updateData)
        .then(() => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        })
        .catch(() => {
          ElMessage.error("修改失败");
        });
    }
  } else {
    // 新增资源
    const addData = {
      requirement_info: {
        file_id: uploadedFileId.value,
        file_name: "requirements.txt",
      },
      resource_info: {
        resource_host: form.value.resource_host,
        resource_port: form.value.resource_port,
        resource_name: form.value.resource_name,
        resource_type: form.value.resource_type,
        resource_status: form.value.resource_status || "停止",
        created_at: new Date().toISOString(),
        python_version: form.value.python_version,
        resource_description: form.value.resource_description,
        redis_url: form.value.redis_url,
        capacity_mode: form.value.capacity_mode,
        capacity_size: form.value.capacity_size,
      },
    };
    addResource(addData)
      .then(() => {
        ElMessage.success("新增成功");
        open.value = false;
        getList();
      })
      .catch(() => {
        ElMessage.error("新增失败");
      });
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  isEdit.value = true;
  isExpand.value = false;
  canEditFields.value = ["resource_name", "resource_description"];
  open.value = true;
  title.value = "编辑资源";

  // 填充表单数据
  form.value = {
    resource_id: row.resource_id,
    resource_name: row.resource_name,
    resource_type: row.resource_type,
    resource_host: row.resource_host,
    resource_port: row.resource_port || 8080,
    resource_status: row.resource_status,
    python_version: row.python_version || "3.8",
    resource_description: row.resource_description || "",
    redis_url: row.redis_url || "127.0.0.1:6379",
    capacity_mode: row.capacity_mode || "手动",
    capacity_size: row.capacity_size || 1,
    requirementFileId: "",
    created_at: row.created_at,
  };
}

/** 删除按钮操作 */
function handleDelete(row) {
  ElMessageBox.confirm(
    '是否确认删除资源编号为"' + row.resourceId + '"的数据项?',
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    delResource(row.resourceId)
      .then(() => {
        getList();
        ElMessage.success("删除成功");
      })
      .catch(() => {
        ElMessage.error("删除失败");
      });
  });
}

/** 扩充资源操作 */
function handleExpand(row) {
  reset();
  isEdit.value = true;
  isExpand.value = true;
  canEditFields.value = ["resource_name", "capacity_mode", "capacity_size"];
  open.value = true;
  title.value = "扩充资源";

  // 填充表单数据
  form.value = {
    resource_id: row.resource_id,
    resource_name: row.resource_name,
    resource_type: row.resource_type,
    resource_host: row.resource_host,
    resource_port: row.resource_port || 8080,
    resource_status: row.resource_status,
    python_version: row.python_version || "3.8",
    resource_description: row.resource_description || "",
    redis_url: row.redis_url || "127.0.0.1:6379",
    capacity_mode: row.capacity_mode || "手动",
    capacity_size: row.capacity_size || 1,
    requirementFileId: "",
    created_at: row.created_at,
  };
}

/** 停止资源操作 */
function handleStop(row) {
  ElMessageBox.confirm(
    '是否确认停止资源编号为"' + row.resourceId + '"的资源?',
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    stopResource(row.resourceId)
      .then(() => {
        getList();
        ElMessage.success("停止成功");
      })
      .catch(() => {
        ElMessage.error("停止失败");
      });
  });
}

/** 启动资源操作 */
function handleStart(row) {
  ElMessageBox.confirm(
    '是否确认启动资源编号为"' + row.resourceId + '"的资源?',
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    startResource(row.resourceId)
      .then(() => {
        getList();
        ElMessage.success("启动成功");
      })
      .catch(() => {
        ElMessage.error("启动失败");
      });
  });
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.resourceId);
  multiple.value = !selection.length;
}

/** 批量删除按钮操作 */
function handleBatchDelete() {
  if (ids.value.length === 0) {
    ElMessage.warning("请选择要删除的资源");
    return;
  }
  ElMessageBox.confirm(
    "是否确认删除选中的" + ids.value.length + "条数据项?",
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    delResourceBatch(ids.value)
      .then(() => {
        getList();
        ElMessage.success("删除成功");
      })
      .catch(() => {
        ElMessage.error("删除失败");
      });
  });
}

onMounted(() => {
  fetchOptions();
  getList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.operation-buttons .el-button {
  padding: 4px 8px;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-upload) {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
}
</style>
